#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
#include <cerrno>
#include <cstdlib>
using namespace std;

const char *path = "/home/sy/lesson24/";
const int proj_id = 0x03;
const int defaultsize = 4096;
string ToHex(key_t key)
{
    char buffer[24];
    snprintf(buffer, sizeof(buffer), "0x%x", key);
    return buffer;
}

key_t GetShmKeyOrDie()
{
    key_t key = ftok(path, proj_id);
    if (key == -1)
    {
        cerr << "ftok failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        exit(100);
    }
    return key;
}

int CreateShmOrDie(key_t key, int size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid == -1)
    {
        cerr << "ftok failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        exit(200);
    }
    return shmid;
}

// 服务端创建shm
key_t CreateShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}
// 客户端访问shm
key_t GetShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT);
}

void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n == -1)
    {
        cerr << "shmctl delete failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        exit(0);
    }
}

void ShmDebug(int shmid)
{
    shmid_ds shmds;
    int n = shmctl(shmid, IPC_STAT, &shmds);
    if (n == -1)
    {
        cerr << "shmctl delete failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        exit(0);
    }
    cout << "shm_segsz:" << shmds.shm_segsz << endl;
    cout << "shm_nattch:" << shmds.shm_nattch << endl;
    cout << "shm_ctime:" << shmds.shm_ctime << endl;
    cout << "shm_perm.__key:" << ToHex(shmds.shm_perm.__key) << endl;
}

//像malloc一样使用ShmAttach
void *ShmAttach(int shmid)
{
    void *addr = shmat(shmid, nullptr, 0);
    if ((long long)addr == -1)
    {
        cerr << "shmat  failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        exit(2);
    }
    return addr;
}

void ShmDetach(void* addr)
{
    int n = shmdt(addr);
    if (n == -1)
    {
        cerr << "shmat  failed, errno: " << errno << ", errstring: " << strerror(errno) << endl;
        exit(3);
    }
}